package com.banksoft.admin.controller;


import com.alibaba.druid.support.monitor.entity.MonitorApp;
import com.banksoft.admin.bean.Mapper;
import com.banksoft.admin.bean.MemberType;
import com.banksoft.admin.bean.OrderStatus;
import com.banksoft.admin.dao.OrderDao;
import com.banksoft.admin.dao.ProductDao;
import com.banksoft.admin.dao.UserDao;
import com.banksoft.admin.entity.*;
import com.banksoft.admin.service.*;
import com.banksoft.common.BaseController;
import com.banksoft.common.PageInfo;
import com.banksoft.util.*;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.print.DocFlavor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * Created by Administrator on 2016/12/1.
 */
@Controller
@RequestMapping("/order/")
public class OrderController extends BaseController {

    @Autowired
    BaseService baseService;
    @Autowired
    OrderProductService orderProductService;
    @Autowired
    ProductService productService;
    @Autowired
    OrderService orderService;
    @Autowired
    OrderFxService orderFxService;

    @RequestMapping("list")
    public String list(){
        return "/order/order_list";
    }

    @RequestMapping("listData")
    @ResponseBody
    public JSONObject listData(HttpServletRequest request, PageInfo pageInfo,String nickName,String account,
                               String startDate, String endDate, String status, String no, String userName,String type,String productName){
        Map<String,Object> map = new HashMap<>();

        if(StringUtil.isNotNull(status)){
            String[] statusArray = null;
            if("1".equals(status)) {
                statusArray =  new String[]{OrderStatus.Pay.name(),OrderStatus.Send.name()};
            }else{
                statusArray = new String[]{status};
            }
            map.put("status",statusArray);
        }
        map.put("no",no);
        map.put("type",type);
        map.put("nickName",nickName);
        map.put("userName",userName);
        map.put("account",account);
        map.put("productName",productName);
        if(StringUtil.isNotNull(startDate)){
            map.put("startDate", DateUtil.getLongFormStrDate(startDate));
        }
        if(StringUtil.isNotNull(endDate))
            map.put("endDate",DateUtil.getLongFormStrDate(endDate));

        pageInfo.setParams(map);
        pageInfo = this.page(OrderDao.class,pageInfo);
        List<Order> list = pageInfo.getResult();
        if(StringUtil.isNotEmpty(list))
            for(Order order:list){
                List<OrderProduct> orderProductList = this.orderProductService.listByOrderId(order.getId());
                if(StringUtil.isNotEmpty(orderProductList)){
                    OrderProduct orderProduct = orderProductList.get(0);
                    order.setProductName(orderProduct.getProductName());
                    order.setProductId(orderProduct.getNum());
                }
                List<OrderFx> fxlist = this.orderFxService.listByOrderId(order.getId());
                String gwFxTotal = "0";
                if(StringUtil.isNotEmpty(fxlist)){
                    for(OrderFx dto:fxlist){
                        gwFxTotal = StringNumber.add(gwFxTotal,dto.getAmount());
                    }
                }
                order.setRemark(gwFxTotal);
            }
        return this.getPageResult(pageInfo);
    }

    @RequestMapping("detail")
    public String find(ModelMap map, String id){
        Order order = this.baseService.findById(OrderDao.class, id);
        if(order!=null){
            List<Product> list = this.productService.listByOrderId(order.getId());
            map.put("list",list);
            /*Product product = this.baseService.findById(ProductDao.class,order.getProductId());
            if(StringUtil.isNotNull(product.getImages())) {
                String[] array = product.getImages().split("\\|");
                map.put("image",array!=null?array[0]:"");
            }*/
            User user = this.baseService.findById(UserDao.class,order.getMemberId());
            map.put("user",user);
        }
        map.put("data", order);
        return "/order/order_view";
    }
    
    @RequestMapping("/updateStatus")
    @ResponseBody
    public JSONObject updateStatus(String id,String status,HttpServletRequest request){
        try{
            Order order = this.baseService.findById(OrderDao.class,id);
            if(order!=null){
                if(status.equals(OrderStatus.Pay.name())){
                    Admin admin = (Admin) getCurrentUser(request);
                    if(!admin.getLoginName().equals("admin"))
                        return this.FmtResult(false,"您没有权限操作",null);
                    this.orderService.updateOrder(order.getNo(),OrderStatus.Pay.name());
                }else {
                    order.setStatus(status);
                    if(OrderStatus.Send.name().equals(status)){
                        order.setSendTime(new Date().getTime());
                    }
                    this.baseService.update(OrderDao.class, order);

                    if(OrderStatus.Send.name().equals(status)){//点击发货时发送模板消息
                      orderService.sendTextMessage(order);
                    }
                }
                return this.FmtResult(true, "操作成功", null);
            }
            return this.FmtResult(false,"没有找到订单",null);
        }catch (Exception e){
            e.printStackTrace();
        }
        return this.FmtResult(false,"操作失败",null);
    }

    //关闭的订单删除
    @RequestMapping("delete")
    @ResponseBody
    public JSONObject delete(String id, HttpServletRequest request){
        Order order = this.baseService.findById(OrderDao.class,id);
        /*if(order != null && !OrderStatus.Close.name().equals(order.getStatus())){
            return this.FmtResult(false,"订单不是关闭状态，不可删除",null);
        }*/
        this.baseService.delete(OrderDao.class, new String[]{id});
        this.saveLog("删除订单："+ order.getNo(),request);
        return this.FmtResult(true,"删除成功",null);
    }

    @RequestMapping("/export")
    @ResponseBody
    public void exportFgData(String startDate, String endDate, String status, String no,String type,String nickName,String account,
            String userName,HttpServletRequest request,HttpServletResponse response){
        Map<String,Object> map = new HashMap<>();
        if(StringUtil.isNotNull(status)){
            String[] statusArray = null;
            if("1".equals(status)) {
                statusArray =  new String[]{OrderStatus.Pay.name(),OrderStatus.Send.name()};
            }else{
                statusArray = new String[]{status};
            }
            map.put("status",statusArray);
        }
        map.put("no",no);
        map.put("userName",userName);
        map.put("nickName",nickName);
        map.put("account",account);
        map.put("type",type);
        if(StringUtil.isNotNull(startDate)){
            map.put("startDate", DateUtil.getLongFormStrDate(startDate));
        }
        if(StringUtil.isNotNull(endDate))
            map.put("endDate",DateUtil.getLongFormStrDate(endDate));

        List<Order> list = orderService.query(map);
        List<Map<String,Object>> data = new ArrayList<>();
        if(StringUtil.isNotEmpty(list)){
            for(Order order:list){
                /*if(OrderStatus.Pay.name().equals(order.getStatus())){
                    //将支付的订单改成发货
                    order.setStatus(OrderStatus.Send.name());
                    order.setSendTime(new Date().getTime());
                    this.baseService.update(OrderDao.class,order);
                    //发送微信消息
                    orderService.sendTextMessage(order);
                }*/
                Map result = new HashMap();
                result.put("no","");
                result.put("userName",order.getUserName());
                result.put("telephone",order.getTelephone());
                result.put("address",order.getProvinceName()+order.getCityName()+order.getAreaName()+"  "+order.getAddress());

                List<OrderProduct> products = this.orderProductService.listByOrderId(order.getId());
                StringBuffer content = new StringBuffer();
                if(StringUtil.isNotEmpty(products)){
                    for(OrderProduct product:products) {
                        content.append(product.getProductName()+"*"+product.getNum()+",");
                    }
                }
                String str = "";
                if(content.length()>0){
                    str = content.substring(0,content.length()-1);
                }
                result.put("remark",str);
                data.add(result);
            }
        }

        String[] keys = {"no","userName","","telephone","address","remark"};
        String[] showNames = new String[]{"订单编号","收件人","电话","手机","地址","发货信息"};

        List<Mapper> mappers = ExcelExportUtil.buildDefaultMapperList(showNames, keys);
        ExcelExportUtil.exportExcel(request,response,"导出订单-"+DateUtil.getFormatDate(new Date(),"yyyyMMdd"),mappers,data,0,0);
    }

    @RequestMapping("/batchSend")
    @ResponseBody
    public JSONObject batchSend(String startDate, String endDate, String status, String no,String type,String nickName,String account,
                                String userName){
        Map<String,Object> map = new HashMap<>();
        if(StringUtil.isNotNull(status)){
            String[] statusArray = null;
            if("1".equals(status)) {
                statusArray =  new String[]{OrderStatus.Pay.name(),OrderStatus.Send.name()};
            }else{
                statusArray = new String[]{status};
            }
            map.put("status",statusArray);
        }
        map.put("no",no);
        map.put("userName",userName);
        map.put("nickName",nickName);
        map.put("account",account);
        map.put("type",type);
        if(StringUtil.isNotNull(startDate)){
            map.put("startDate", DateUtil.getLongFormStrDate(startDate));
        }
        if(StringUtil.isNotNull(endDate))
            map.put("endDate",DateUtil.getLongFormStrDate(endDate));

        List<Order> list = orderService.query(map);
        if(StringUtil.isNotEmpty(list)) {
            for (Order order : list) {
                if (OrderStatus.Pay.name().equals(order.getStatus())) {
                    //将支付的订单改成发货
                    order.setStatus(OrderStatus.Send.name());
                    order.setSendTime(new Date().getTime());
                    this.baseService.update(OrderDao.class, order);
                    //发送微信消息
                    orderService.sendTextMessage(order);
                }
            }
        }
        return this.FmtResult(true,null,null);
    }

    @RequestMapping("/save")
    @ResponseBody
    public JSONObject save(String id,String billNo){
        try{
            Order order = this.baseService.findById(OrderDao.class,id);
            if(order!=null) {
                order.setBillNo(billNo);
                this.baseService.update(OrderDao.class,order);
                return this.FmtResult(true,"保存成功",null);
            }
            return this.FmtResult(false,"没有找到订单信息",null);
        }catch (Exception e){
            e.printStackTrace();
        }
        return this.FmtResult(false,"保存失败",null);
    }

    @RequestMapping("/beforeImport")
    public String beforeImport(){
        return "order/import";
    }


    @RequestMapping("/import")
    @ResponseBody
    public JSONObject importExcel(String fileName,HttpServletRequest request){
        try{
            String path = request.getServletContext().getRealPath("/")+fileName;
            List<Map> list = ExcelUtil.readExcel(path);
            int count = 0;
            if(StringUtil.isNotEmpty(list)){
                for(Map map:list){
                    String orderNo = (String) map.get("orderNo");
                    String sendNo = (String) map.get("sendNo");
                    List<Order> orders = this.orderService.listByOrderNo(orderNo);
                    if(StringUtil.isNotEmpty(orders)){
                        Order order = orders.get(0);
                        order.setBillNo(sendNo);
                        this.baseService.update(OrderDao.class,order);
                        count ++;
                    }
                }
            }
            return this.FmtResult(true,"成功导入数据："+count,null);
        }catch (Exception e){
            e.printStackTrace();
        }
        return this.FmtResult(false,"导入失败，请检查文件格式！",null);
    }

}
